package com.hazy.animalface.view;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVFile;
import com.hazy.animalface.R;
import com.hazy.animalface.adapter.UploadStickerListAdapter;
import com.hazy.animalface.module.Sticker;
import com.hazy.animalface.module.StickerBag;
import com.hazy.animalface.presenter.ILoadPresenter;
import com.hazy.animalface.presenter.ILoadPresenterCompl;
import com.hazy.animalface.utils.ImageToByte;
import com.umeng.socialize.UMShareAPI;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.PhotoPreview;

/**
 * Created by Jiaui on 2017/4/15 0015.
 * <p>
 * 创建一个头贴包的界面
 */
public class CreateStickerBagActivity extends AppCompatActivity implements ILoadView {

    @Bind(R.id.toolbar)
    Toolbar toolbar;                         // 工具栏
    @Bind(R.id.stickerbag_name)
    AutoCompleteTextView stickerbagName;     // 名称
    @Bind(R.id.stickerbag_price)
    AutoCompleteTextView stickerbagPrice;    // 价格
    @Bind(R.id.stickers_list)
    RecyclerView stickersList;               // 上传列表

    private TextView mProgressTextView;      // 进度显示
    private AlertDialog progressDialog;      // 进度对话框

    private ILoadPresenter iLoadPresenter;

    private ArrayList<String> stickerList;
    private UploadStickerListAdapter uploadStickerListAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_stickerbag);
        ButterKnife.bind(this);

        // 设置工具栏
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle(getString(R.string.create_stickerbag_title));
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        iLoadPresenter = new ILoadPresenterCompl(this);
        stickerList = new ArrayList<>();
        stickersList.setLayoutManager(new GridLayoutManager(this, 3));
        uploadStickerListAdapter = new UploadStickerListAdapter(this, stickerList);
        stickersList.setAdapter(uploadStickerListAdapter);
    }

    @OnClick(R.id.create_stickerbag_btn)
    public void onClick() {

        String stikerbagName = stickerbagName.getText().toString().trim();
        if (stikerbagName == null || "".equals(stikerbagName)) {
            Toast.makeText(this, "请输入名称", Toast.LENGTH_LONG).show();
            return;
        }

        String stikerbagPrice = stickerbagPrice.getText().toString().trim();
        if (stikerbagPrice == null || "".equals(stikerbagPrice)) {
            Toast.makeText(this, "请输入价格", Toast.LENGTH_LONG).show();
            return;
        }

        if (stickerList == null || stickerList.size() < 1) {
            Toast.makeText(this, "请选择头贴", Toast.LENGTH_LONG).show();
            return;
        }

        try {
            View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_upload_progress, null);
            mProgressTextView = (TextView) dialogView.findViewById(R.id.uploading_count_tv);
            mProgressTextView.setText("0 / " + stickerList.size());
            progressDialog = new AlertDialog.Builder(this).setTitle(getString(R.string.uploading)).setView(dialogView).create();
            progressDialog.show();
            progressDialog.setCanceledOnTouchOutside(false);
            byte[] bytes = ImageToByte.getBytes(new FileInputStream(stickerList.get(0)));
            AVFile thumbFile = new AVFile(stikerbagName, bytes);
            iLoadPresenter.createStickerBag(stikerbagName, stikerbagPrice, thumbFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                // 选择相片返回
                case PhotoPicker.REQUEST_CODE:
                    if (data != null) {
                        ArrayList<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                        if (stickerList != null && stickerList.size() + photos.size() > 20) {
                            Toast.makeText(CreateStickerBagActivity.this, "选择的头贴数量已达上限", Toast.LENGTH_LONG).show();
                            return;
                        }
                        stickerList.addAll(photos);
                        uploadStickerListAdapter.notifyDataSetChanged();
                    }
                    break;
                // 预览选择的相片，如果删除了部分，那么返回剩下的
                case PhotoPreview.REQUEST_CODE:
                    ArrayList<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                    if (stickerList == null) {
                        stickerList = new ArrayList<>();
                    }
                    if (photos!=null && stickerList.size() == photos.size()) return;
                    stickerList.clear();
                    stickerList.addAll(photos);
                    uploadStickerListAdapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }

    @Override
    public void onLoadResult(List<StickerBag> stickerBags) {

    }

    @Override
    public void onLoadSrickerDetail(boolean result, List<Sticker> stickers) {

    }

    @Override
    public void onCreateResult(boolean result, String message) {
        if (result) {
            String stikerbagName = stickerbagName.getText().toString().trim();
            iLoadPresenter.uploadStickers(stikerbagName, stickerList);
        } else {
            if (progressDialog != null) {
                progressDialog.dismiss();
            }
        }
    }

    @Override
    public void onUploadResult(boolean result, int progress, String message) {
        mProgressTextView.setText(progress + " / " + stickerList.size());
        if (progress == stickerList.size()) {
            progressDialog.dismiss();
            Toast.makeText(this, "上传成功", Toast.LENGTH_LONG).show();
            finish();
        }
    }
}
